package com.alibaba.citrus.cr.sales.plan.facade.service.salesplan;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.common.model.ApiContext;
import com.alibaba.citrus.cr.common.util.DateUtils;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.SalesPlanLineQueryService;
import com.alibaba.citrus.cr.sales.plan.dto.api.response.SalesPlanSubTotalResponse;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesPlanStatusEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesStatBizTypeEnum;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanLineRepository;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanLineSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanSDO;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.DimensionDTO;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.PageQueryPlanLineRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanSubTotalRequest;
import com.alibaba.citrus.cr.sales.plan.facade.service.SalesPlanCommonService;
import com.alibaba.citrus.cr.sales.plan.facade.service.SalesPlanOutCommonService;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.esdegrade.dto.GetEsDegradeValueResponse;
import com.epoch.app.bcorder.esdegrade.service.EsDegradeService;
import com.epoch.app.bcorder.model.dto.ScItemSDO;
import com.epoch.app.bcorder.sales_plan.bosalesplandetailindex.dto.PageQueryPlanDetailAndAdjustDetailRequest;
import com.epoch.app.bcorder.sales_plan.bosalesplandetailindex.dto.PageQueryPlanDetailAndAdjustDetailResponse;
import com.epoch.app.bcorder.sales_plan.bosalesplandetailindex.dto.PageQueryPlanDetailRequest;
import com.epoch.app.bcorder.sales_plan.bosalesplandetailindex.dto.PageQueryPlanDetailResponse;
import com.epoch.app.bcorder.sales_plan.bosalesplandetailindex.service.BoSalesPlanDetailIndexService;
import com.epoch.app.bcorder.sales_plan.contract.dto.SubTotalCompanyCrmContractCountRequest;
import com.epoch.app.bcorder.sales_plan.contract.model.Contract;
import com.epoch.app.bcorder.sales_plan.contract.service.ContractService;
import com.epoch.app.bcorder.sales_plan.planscitemextend.dto.SubTotalCompanyReturnCountRequest;
import com.epoch.app.bcorder.sales_plan.planscitemextend.dto.SubTotalCompanyReturnCountResponse;
import com.epoch.app.bcorder.sales_plan.planscitemextend.service.PlanScItemExtendService;
import com.epoch.app.bcorder.sales_plan.salesplandetail.dto.QueryPlanDetailByDbRequest;
import com.epoch.app.bcorder.sales_plan.salesplandetail.dto.QueryPlanDetailByDbResponse;
import com.epoch.app.bcorder.sales_plan.salesplandetail.dto.SubTotalSalesPlanLineRequest;
import com.epoch.app.bcorder.sales_plan.salesplandetail.service.SalesPlanDetailService;
import com.epoch.app.crplatformenhance.enums.OrganizationTypeEnum;
import com.epoch.app.crplatformenhance.model.dto.CustomerAddressIndex;
import com.epoch.app.crunifiedinventory.model.dto.GetStoreInventoryAggreRequest;
import com.epoch.app.crunifiedinventory.model.dto.WarehouseInventory;
import com.epoch.app.crunifiedinventory.service.CrUnifiedInventoryService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author wangyibing
 */
@Service
public class SalesPlanLineQueryServiceImpl implements SalesPlanLineQueryService {

    private static final Log log = Log.getLogger(SalesPlanLineQueryServiceImpl.class);

    @Resource
    private BoSalesPlanDetailIndexService boSalesPlanDetailIndexService;

    @Resource
    private SalesPlanLineRepository salesPlanLineRepository;

    @Resource
    private SalesPlanCommonService salesPlanCommonService;

    @Resource
    private SalesPlanOutCommonService salesPlanOutCommonService;

    @Autowired(required = false)
    private CrUnifiedInventoryService crUnifiedInventoryService;

    @Resource
    private PlanScItemExtendService planScItemExtendService;

    @Resource
    private ContractService contractService;

    @Resource
    private EsDegradeService esDegradeService;

    @Resource
    private SalesPlanDetailService salesPlanDetailService;

    @Override
    @FacadeInvoker
    public Result<PageResult<List<SalesPlanLineSDO>>> pageQuerySalesPlanLineList(PageQueryPlanLineRequest queryPlanLineRequest) {
        SalesPlanSDO salesPlan = salesPlanCommonService.checkSalesPlan(queryPlanLineRequest.getPlanId());
        PageQueryPlanDetailRequest detailRequest = getPageQueryPlanDetailRequest(queryPlanLineRequest,salesPlan);

        PageQueryPlanDetailResponse planDetailResponse = new PageQueryPlanDetailResponse();
        GetEsDegradeValueResponse esDegradeValue = esDegradeService.getEsDegradeValue();
        if(queryPlanLineRequest.getShowAdjustDetail() != null && queryPlanLineRequest.getShowAdjustDetail()){
            // es 降级开关 若开关开启，需要走db降级查询 开关未开启，走原有逻辑
            if (esDegradeValue != null && esDegradeValue.getResult()){
                QueryPlanDetailByDbRequest queryPlanDetailByDb = QueryPlanDetailByDbRequest.builder().build();
                BeanUtils.copyProperties(detailRequest,queryPlanDetailByDb);
                QueryPlanDetailByDbResponse queryPlanDetailByDbResponse = salesPlanDetailService.queryPlanDetailByDb(queryPlanDetailByDb);
                BeanUtils.copyProperties(queryPlanDetailByDbResponse,planDetailResponse);
            }else {
                PageQueryPlanDetailAndAdjustDetailRequest detailRequest2 = new PageQueryPlanDetailAndAdjustDetailRequest();
                BeanUtils.copyProperties(detailRequest, detailRequest2);
                PageQueryPlanDetailAndAdjustDetailResponse planDetailResponse2 = boSalesPlanDetailIndexService.pageQueryPlanDetailAndAdjustDetail(detailRequest2);
                BeanUtils.copyProperties(planDetailResponse2, planDetailResponse);
            }

        }else{
            // es 降级开关 若开关开启，需要走db降级查询 开关未开启，走原有逻辑
            if (esDegradeValue != null && esDegradeValue.getResult()){
                QueryPlanDetailByDbRequest queryPlanDetailByDb = QueryPlanDetailByDbRequest.builder().build();
                BeanUtils.copyProperties(detailRequest,queryPlanDetailByDb);
                QueryPlanDetailByDbResponse queryPlanDetailByDbResponse = salesPlanDetailService.queryPlanDetailByDb(queryPlanDetailByDb);
                BeanUtils.copyProperties(queryPlanDetailByDbResponse,planDetailResponse);
            }else {
                planDetailResponse = boSalesPlanDetailIndexService.pageQueryPlanDetail(detailRequest);
            }

        }
        if (planDetailResponse != null && CollectionUtils.isEmpty(planDetailResponse.getResult())) {
            return Result.success(new PageResult<>(Lists.newArrayList(), 0));
        }
        List<SalesPlanLineSDO> collect = planDetailResponse.getResult().stream().map(detail -> {
            SalesPlanLineSDO sdo = SalesPlanLineSDO.builder().build();
            BeanUtils.copyProperties(detail, sdo);
            sdo.setPlanId(String.valueOf(detail.getPlanId()));
            sdo.setCustomerName(detail.getSubCustomerName());
            sdo.setCustomerAddressName(detail.getSubCustomerAddressName());
            //20240523 兼容一盘货计划明细售达方维度导入
            if (StringUtils.isBlank(sdo.getCustomerAddress())) {
                sdo.setCustomerAddress(sdo.getCustomerCode());
            }
            if (StringUtils.isBlank(sdo.getCustomerAddressName())) {
                sdo.setCustomerAddressName(sdo.getCustomerName());
            }
            sdo.setScItemName(detail.getSubScItemName());
            sdo.setMonthReturnCount(sdo.getMonthFirstReturnCount() + sdo.getMonthMiddleReturnCount() + sdo.getMonthLastReturnCount());
            sdo.setMonthAdjustReturnCount(sdo.getMonthFirstAdjustReturnCount() + sdo.getMonthMiddleAdjustReturnCount() + sdo.getMonthLastAdjustReturnCount());
            sdo.setAppletSubmission(detail.getAppletSubmission() == null?false:detail.getAppletSubmission());
            sdo.setGmtCreate(detail.getGmt_create());
            sdo.setGmtModified(detail.getGmt_modified());
            sdo.setIsAllowDelete(!"1".equals(detail.getParam1()));
            return sdo;
        }).collect(Collectors.toList());
        PageResult<List<SalesPlanLineSDO>> pageResult = new PageResult<>(collect, planDetailResponse.getTotal());
        if (collect.size() > 0) {
            pageResultConverter(pageResult);
        }
        return Result.success(pageResult);
    }

    private PageQueryPlanDetailRequest getPageQueryPlanDetailRequest(PageQueryPlanLineRequest queryPlanLineRequest,SalesPlanSDO salesPlan) {
        PageQueryPlanDetailRequest detailRequest = new PageQueryPlanDetailRequest();
//        SalesPlanSDO salesPlan = salesPlanCommonService.checkSalesPlan(queryPlanLineRequest.getPlanId());
        DimensionDTO dimension = salesPlanCommonService.checkBizType(salesPlan, queryPlanLineRequest);
        SalesStatBizTypeEnum byOrganizationType = SalesStatBizTypeEnum.match(dimension.getBizType());
        switch (byOrganizationType) {
            case SALESMAN:
                detailRequest.setManageEmployeeIdList(Lists.newArrayList(dimension.getBizId()));
                break;
            case SALES_DEPARTMENT:
                detailRequest.setOrgSalesDepartmentCode(dimension.getBizId());
                break;
            case SALES_CHANNEL:
                detailRequest.setOrgSalesChannelCode(dimension.getBizId());
                break;
            case SALES_ORGANIZATION:
                detailRequest.setOrgSalesOrganizationCode(dimension.getBizId());
                break;
            case BUSINESS_UNIT:
                detailRequest.setOrgBusinessUnitCode(dimension.getBizId());
                break;
            default:
        }
        detailRequest.setAsc(queryPlanLineRequest.getAsc() == null || queryPlanLineRequest.getAsc());
        detailRequest.setField(queryPlanLineRequest.getDir());
        detailRequest.setPlanId(Long.valueOf(queryPlanLineRequest.getPlanId()));
        detailRequest.setChannelCode(queryPlanLineRequest.getChannelCode());

        if (StringUtils.isNotBlank(queryPlanLineRequest.getCustomerCode())) {
            detailRequest.setCustomerCodeList(Lists.newArrayList(queryPlanLineRequest.getCustomerCode()));
        }
        if (StringUtils.isNotBlank(queryPlanLineRequest.getCustomerAddress())) {
            detailRequest.setCustomerAddress(queryPlanLineRequest.getCustomerAddress());
        }
        if (CollectionUtils.isNotEmpty(queryPlanLineRequest.getCustomerAddresss())) {
            detailRequest.setCustomerAddressList(queryPlanLineRequest.getCustomerAddresss());
        }
        if (StringUtils.isNotBlank(queryPlanLineRequest.getManageEmployeeId())) {
            detailRequest.setManageEmployeeIdList(Lists.newArrayList(queryPlanLineRequest.getManageEmployeeId()));
        }

        List<String> scItemIdList = new ArrayList<>();
        if (StringUtils.isNotBlank(queryPlanLineRequest.getScItemId())) {
            scItemIdList.add(queryPlanLineRequest.getScItemId());
        }
        if (CollectionUtils.isNotEmpty(queryPlanLineRequest.getScItemIdList())) {
            scItemIdList.addAll(queryPlanLineRequest.getScItemIdList());
        }
        if (StringUtils.isNotBlank(queryPlanLineRequest.getScItemCode())) {
            Map<String, ScItemSDO> scItemMap = salesPlanOutCommonService.getScItemMapByOutId(Sets.newHashSet(queryPlanLineRequest.getScItemCode()));
            if(scItemMap != null){
                scItemIdList.addAll(scItemMap.values().stream().map(x->x.getScItemId()).collect(Collectors.toList()));
            }else{
                scItemIdList.add("-1");
            }
        }
        if(CollectionUtils.isNotEmpty(scItemIdList)){
            detailRequest.setScItemIdList(scItemIdList);
        }

        if (StringUtils.isNotBlank(queryPlanLineRequest.getScItemGroup())) {
            detailRequest.setScItemGroupList(Lists.newArrayList(queryPlanLineRequest.getScItemGroup()));
        }

        List<String> scItemLeafCategoryIdList = new ArrayList<>();
        if (StringUtils.isNotBlank(queryPlanLineRequest.getScItemLeafCategoryId())) {
            scItemLeafCategoryIdList.add(queryPlanLineRequest.getScItemLeafCategoryId());
        }
        if (CollectionUtils.isNotEmpty(queryPlanLineRequest.getScItemLeafCategoryIdList())) {
            scItemLeafCategoryIdList.addAll(queryPlanLineRequest.getScItemLeafCategoryIdList());
        }
        if (CollectionUtils.isNotEmpty(scItemLeafCategoryIdList)) {
            detailRequest.setScItemLeafCategoryIdList(scItemLeafCategoryIdList);
        }

        if (StringUtils.isNotBlank(queryPlanLineRequest.getCustomerAddressId())) {
            detailRequest.setCustomerAddressId(queryPlanLineRequest.getCustomerAddressId());
        }

        detailRequest.setAppletSubmission(queryPlanLineRequest.getAppletSubmission());
        //2023.04.04 重新放开状态
        detailRequest.setStatus(queryPlanLineRequest.getStatus());
        detailRequest.setContractDifferenceMoneyStamp(queryPlanLineRequest.getContractDifferenceMoneyStamp());
        detailRequest.setCustomerName(queryPlanLineRequest.getCustomerName());
        detailRequest.setCustomerAddressName(queryPlanLineRequest.getCustomerAddressName());
        detailRequest.setScItemName(queryPlanLineRequest.getScItemName());
        detailRequest.setStart(queryPlanLineRequest.getStart());
        detailRequest.setLimit(queryPlanLineRequest.getLimit());
        return detailRequest;
    }

    private void pageResultConverter(PageResult<List<SalesPlanLineSDO>> pageResult) {
        Set<String> scItemSet = Sets.newHashSet();
        Set<String> customerAddressSet = Sets.newHashSet();
        Set<String> customerSet = Sets.newHashSet();
        Set<String> orgSalesOrganizationCodeSet = Sets.newHashSet();
        Set<String> channelCodeSet = Sets.newHashSet();
        pageResult.getContent().forEach(salesPlanLineSDO -> {
            scItemSet.add(salesPlanLineSDO.getScItemId());
            if (StringUtils.isNotBlank(salesPlanLineSDO.getCustomerAddress())) {
                customerAddressSet.add(salesPlanLineSDO.getCustomerAddress());
            }
            customerSet.add(salesPlanLineSDO.getCustomerCode());
            orgSalesOrganizationCodeSet.add(salesPlanLineSDO.getOrgSalesOrganizationCode());
            channelCodeSet.add(salesPlanLineSDO.getChannelCode());
        });
        //获取货品外部编码
        Map<String, ScItemSDO> scItemMapByOutMap = salesPlanOutCommonService.getScItemMapByIds(scItemSet, false);
        if (scItemMapByOutMap == null){
            log.error("SalesPlanLineQueryServiceImpl.pageResultConverter scItemMapByOutMap is null");
            return;
        }
        //获取客户地址
        Map<String, CustomerAddressIndex> customerAddressByFive = salesPlanOutCommonService.getCustomerAddressByFive(customerAddressSet, customerSet, orgSalesOrganizationCodeSet, channelCodeSet, null);
        if(null == customerAddressByFive){
            log.error("SalesPlanLineQueryServiceImpl.pageResultConverter customerAddressByFive is null");
            return;
        }
        List<String> addressIdCollect = customerAddressByFive.values().stream().map(index -> {
            return Objects.toString(index.getId());
        }).collect(Collectors.toList());

        //取门店库存
        Map<String, WarehouseInventory> businessInventoryMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(addressIdCollect)) {
            GetStoreInventoryAggreRequest getStoreInventoryAggreRequest = new GetStoreInventoryAggreRequest();
            getStoreInventoryAggreRequest.setAddressCodeList(addressIdCollect);
            getStoreInventoryAggreRequest.setGoodsIds(Lists.newArrayList(scItemSet));
            try {
                Result<List<WarehouseInventory>> listResult = crUnifiedInventoryService.getStoreInventoryAggre(getStoreInventoryAggreRequest);
                if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())){
                    businessInventoryMap = listResult.getResult()
                            .stream().collect(Collectors.toMap(x -> x.getGoodsId() + x.getAddressCode(), a -> a, (a, b) -> a));
                }
            }catch (Exception e){
                log.error("SalesPlanLineQueryServiceImpl.searchBusinessInventoryByPage.exception:{}",e);
            }
        }

        for (SalesPlanLineSDO salesPlanLineSDO : pageResult.getContent()) {
            salesPlanLineSDO.setInventory(0);
            if (!Objects.isNull(scItemMapByOutMap) && !scItemMapByOutMap.isEmpty()) {
                ScItemSDO scItemSDO = scItemMapByOutMap.get(salesPlanLineSDO.getScItemId());
                if (Objects.nonNull(scItemSDO)) {
                    //外部编码
                    salesPlanLineSDO.setOuterId(scItemSDO.getOuterId());
                }
            }
            CustomerAddressIndex customerAddressIndex = customerAddressByFive.get(salesPlanLineSDO.getCustomerCode() + salesPlanLineSDO.getCustomerAddress() + salesPlanLineSDO.getOrgSalesOrganizationCode() + salesPlanLineSDO.getChannelCode());
            if (customerAddressIndex == null) {
                salesPlanLineSDO.setInventoryStr("0");
                continue;
            }
            WarehouseInventory warehouseInventory = businessInventoryMap.get(salesPlanLineSDO.getScItemId() + customerAddressIndex.getId());
            if (Objects.nonNull(warehouseInventory)) {
                salesPlanLineSDO.setInventoryStr(warehouseInventory.getAvailableQuantityFormat());
            } else {
                salesPlanLineSDO.setInventoryStr("0");
            }
        }
    }

    @Override
    @FacadeInvoker
    public Result<SalesPlanSubTotalResponse> subTotalSalesPlanLine(SalesPlanSubTotalRequest salesPlanSubTotalRequest) {
        SalesPlanSDO salesPlan = salesPlanCommonService.checkSalesPlan(String.valueOf(salesPlanSubTotalRequest.getPlanId()));
        PageQueryPlanLineRequest pageQueryPlanLineRequest = new PageQueryPlanLineRequest();
        BeanUtils.copyProperties(salesPlanSubTotalRequest,pageQueryPlanLineRequest);
        pageQueryPlanLineRequest.setPlanId(String.valueOf(salesPlanSubTotalRequest.getPlanId()));
        if (CollectionUtils.isNotEmpty(salesPlanSubTotalRequest.getCustomerAddressList())) {
            pageQueryPlanLineRequest.setCustomerAddresss(salesPlanSubTotalRequest.getCustomerAddressList());
        }
        PageQueryPlanDetailRequest pageQueryPlanDetailRequest = getPageQueryPlanDetailRequest(pageQueryPlanLineRequest,salesPlan);
        SubTotalSalesPlanLineRequest subTotalRequest = new SubTotalSalesPlanLineRequest();
        BeanUtils.copyProperties(pageQueryPlanDetailRequest,subTotalRequest);

        //合计月度计划明细
        SalesPlanSubTotalResponse salesPlanSubTotalResponse = salesPlanLineRepository.subTotalSalesPlanLine(subTotalRequest);
        BigDecimal discount = (new BigDecimal(100).subtract(salesPlan.getEstimateDiscount())).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);
        if(salesPlanSubTotalResponse.getBeforeAdjustMoney()!=null){
            BigDecimal adjustMoney = new BigDecimal(salesPlanSubTotalResponse.getBeforeAdjustMoney()).multiply(discount);
            salesPlanSubTotalResponse.setAdjustMoney(adjustMoney.longValue());
        }
        //初始任务量
        if(salesPlan.getStatus()>= SalesPlanStatusEnum.PUBLISHED.getCode()){
            if(salesPlanSubTotalResponse.getInitBeforeTaskMoney()!=null){
                BigDecimal initTaskMoney = new BigDecimal(salesPlanSubTotalResponse.getInitBeforeTaskMoney()).multiply(discount);
                salesPlanSubTotalResponse.setInitTaskMoney(initTaskMoney.longValue());
            }
        }else{
            salesPlanSubTotalResponse.setInitTaskCount(0);
            salesPlanSubTotalResponse.setInitBeforeTaskMoney(0L);
            salesPlanSubTotalResponse.setInitTaskMoney(0L);
        }

        if(salesPlanSubTotalResponse.getMonthCount()!=null){
            //合计crm回复量
            SubTotalCompanyReturnCountRequest subTotalReturnCountRequest = new SubTotalCompanyReturnCountRequest();
            BeanUtils.copyProperties(subTotalRequest, subTotalReturnCountRequest);
            SubTotalCompanyReturnCountResponse subTotalCompanyReturnCountResponse = planScItemExtendService.subTotalCompanyReturnCount(subTotalReturnCountRequest);
            salesPlanSubTotalResponse.setReturnCount(getMoney(subTotalCompanyReturnCountResponse.getReturnCount()));
            salesPlanSubTotalResponse.setBeforeReturnMoney(getMoney(subTotalCompanyReturnCountResponse.getBeforeReturnMoney()));
            BigDecimal returnMoney = new BigDecimal(salesPlanSubTotalResponse.getBeforeReturnMoney()).multiply(discount);
            salesPlanSubTotalResponse.setReturnMoney(returnMoney.longValue());
            salesPlanSubTotalResponse.setReturnOutboundMoney(getMoney(subTotalCompanyReturnCountResponse.getReturnOutboundMoney()));

            //合计crm合同量
            SubTotalCompanyCrmContractCountRequest subTotalCompanyCrmContractCountRequest = new SubTotalCompanyCrmContractCountRequest();
            subTotalCompanyCrmContractCountRequest.setContractYear(DateUtils.toDateStr(Long.valueOf(salesPlan.getPlanTime()),"yyyy"));
            subTotalCompanyCrmContractCountRequest.setOrgBusinessUnitCode(salesPlan.getOrgBusinessUnitCode());
            subTotalCompanyCrmContractCountRequest.setScItemIdList(subTotalRequest.getScItemIdList());
            subTotalCompanyCrmContractCountRequest.setScItemCategoryIdList(subTotalRequest.getScItemLeafCategoryIdList());
            Result<Contract> contractResult = contractService.subTotalCompanyCrmContractCount(subTotalCompanyCrmContractCountRequest);
            Contract contract = contractResult.getResult();
            setSubTotalContractCount(DateUtils.toDateStr(Long.valueOf(salesPlan.getPlanTime()),"MM"),contract,salesPlanSubTotalResponse);
        }

        return Result.success(salesPlanSubTotalResponse);
    }

    public void setSubTotalContractCount(String month, Contract contract,SalesPlanSubTotalResponse salesPlanSubTotalResponse){
        Long crmMonthContractCount = null;
        Long crmBeforeMonthContractMoney = null;
        Long crmMonthContractMoney = null;
        switch (month){
            case "01" :
                crmMonthContractCount = getCount(contract.getJanQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getJanTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getJanAmount());
                break;
            case "02" :
                crmMonthContractCount = getCount(contract.getFebQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getFebTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getFebAmount());
                break;
            case "03" :
                crmMonthContractCount = getCount(contract.getMarQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getMarTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getMarAmount());
                break;
            case "04" :
                crmMonthContractCount = getCount(contract.getAprQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getAprTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getAprAmount());
                break;
            case "05" :
                crmMonthContractCount = getCount(contract.getMayQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getMayTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getMayAmount());
                break;
            case "06" :
                crmMonthContractCount = getCount(contract.getJuneQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getJuneTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getJuneAmount());
                break;
            case "07" :
                crmMonthContractCount = getCount(contract.getJulyQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getJulyTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getJulyAmount());
                break;
            case "08" :
                crmMonthContractCount = getCount(contract.getAugQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getAugTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getAugAmount());
                break;
            case "09" :
                crmMonthContractCount = getCount(contract.getSeptQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getSeptTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getSeptAmount());
                break;
            case "10" :
                crmMonthContractCount = getCount(contract.getOctQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getOctTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getOctAmount());
                break;
            case "11" :
                crmMonthContractCount = getCount(contract.getNovQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getNovTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getNovAmount());
                break;
            case "12" :
                crmMonthContractCount = getCount(contract.getDecQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getDecTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getDecAmount());
                break;
            default:
                crmMonthContractCount = 0L;
                crmBeforeMonthContractMoney = 0L;
                crmMonthContractMoney = 0L;
        }

        salesPlanSubTotalResponse.setCrmMonthContractCount(crmMonthContractCount);
        salesPlanSubTotalResponse.setCrmBeforeMonthContractMoney(crmBeforeMonthContractMoney);
        salesPlanSubTotalResponse.setCrmMonthContractMoney(crmMonthContractMoney);
    }

    private Long getCount(Integer i){
        if(i == null){
            return 0L;
        }
        return i.longValue();
    }

    private Long getMoney(Long l){
        if(l == null){
            return 0L;
        }
        return l;
    }

    @Override
    @FacadeInvoker
    public Result<BigDecimal> queryCompletePercent(SalesPlanSubTotalRequest salesPlanSubTotalRequest) {
        SalesPlanSDO salesPlan = salesPlanCommonService.checkSalesPlan(String.valueOf(salesPlanSubTotalRequest.getPlanId()));
        DimensionDTO dimension = salesPlanCommonService.checkBizType(salesPlan, salesPlanSubTotalRequest);
        SalesStatBizTypeEnum byOrganizationType = SalesStatBizTypeEnum.match(dimension.getBizType());
        switch (byOrganizationType) {
            case SALESMAN:
                salesPlanSubTotalRequest.setManageEmployeeId(dimension.getBizId());
                break;
            case SALES_DEPARTMENT:
                salesPlanSubTotalRequest.setOrgSalesDepartmentCode(dimension.getBizId());
                break;
            case SALES_CHANNEL:
                salesPlanSubTotalRequest.setOrgSalesChannelCode(dimension.getBizId());
                break;
            case SALES_ORGANIZATION:
                salesPlanSubTotalRequest.setOrgSalesOrganizationCode(dimension.getBizId());
                break;
            case BUSINESS_UNIT:
                salesPlanSubTotalRequest.setOrgBusinessUnitCode(dimension.getBizId());
                break;
            default:
        }
        return Result.success(salesPlanLineRepository.queryCompletePercent(salesPlanSubTotalRequest));
    }

    @Override
    @FacadeInvoker
    public Result<List<String>> querySalesPlanLineByCustomerAddress(SalesPlanSubTotalRequest salesPlanSubTotalRequest) {
        return Result.success(salesPlanLineRepository.querySalesPlanLineByCustomerAddress(salesPlanSubTotalRequest));
    }

    @Override
    @FacadeInvoker
    public Result<List<String>> querySalesPlanLineByScItem(SalesPlanSubTotalRequest salesPlanSubTotalRequest) {
        return Result.success(salesPlanLineRepository.querySalesPlanLineByScItem(salesPlanSubTotalRequest));
    }

    @Override
    @FacadeInvoker
    public Result<PageResult<List<SalesPlanLineSDO>>> pageQuerySalesPlanLineListFromDb(PageQueryPlanLineRequest pageQuerySalePlanRequest) {
        SalesPlanSDO salesPlan = salesPlanCommonService.checkSalesPlan(pageQuerySalePlanRequest.getPlanId());
        PageQueryPlanDetailRequest detailRequest = getPageQueryPlanDetailRequest(pageQuerySalePlanRequest,salesPlan);
        BeanUtils.copyProperties(detailRequest,pageQuerySalePlanRequest);
        PageResult<List<SalesPlanLineSDO>> result = salesPlanLineRepository.pageQuerySalesPlanLineList(pageQuerySalePlanRequest);
        return Result.success(result);
    }

    private Result<Boolean> salesPlanData(ApiContext apiContext, PageQueryPlanLineRequest pageQueryPlanLineRequest) {
        if (apiContext.getIsSales() != null && apiContext.getIsSales()) {
            if (StringUtils.isNotEmpty(pageQueryPlanLineRequest.getManageEmployeeId())) {
                if (!apiContext.getEmployeeId().equals(pageQueryPlanLineRequest.getManageEmployeeId())) {
                    throw new FacadeException("OTS-01-003-01-16-002");
                }
            }
            return Result.success(true);
        }
        OrganizationTypeEnum typeEnum = Arrays.stream(OrganizationTypeEnum.values()).filter(
                        s -> s.getCode().equals(pageQueryPlanLineRequest.getBizType()))
                .findFirst().orElse(null);
        if (Objects.isNull(typeEnum)) {
            throw new FacadeException("OTS-01-003-01-16-001");
        }
        if (apiContext.getRelatedOrganizationType() > pageQueryPlanLineRequest.getBizType()) {
            throw new FacadeException("OTS-01-003-01-16-002");
        }
        if (apiContext.getRelatedOrganizationType().equals(pageQueryPlanLineRequest.getBizType())) {
            if (!apiContext.getBelongOrganizationId().equals(pageQueryPlanLineRequest.getBizId())) {
                throw new FacadeException("OTS-01-003-01-16-002");
            }
        }
        return Result.success(true);
    }

}
